/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package almacen;

import com.mxrck.autocompleter.TextAutoCompleter;
import java.awt.Image;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
import java.util.logging.Level;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import resources.local_connection;
import resources.queries;

/**
 *
 * @author Tesla
 */
public class EditProducto extends javax.swing.JFrame {

    Connection cn;
    PreparedStatement ps;
    ResultSet rs;
    ResultSetMetaData rsm;
    static int code;
    static int id_proveedor;
    boolean hayImagen=false;
    Vector ext = new Vector(5,1);
    Vector img = new Vector(5,1);
    Vector imgId = new Vector(5,1);
TextAutoCompleter textAutoCompleter;
    /**
     * Creates new form propiedades
     * @param cd
     */
    public EditProducto(int cd) {
        initComponents();
        if(Almacen.celulares)
        {
            tipo.removeAllItems();
            tipo.addItem("Producto");
            tipo.addItem("Celular");
            tipo.addItem("Chip");
        }
        code = cd;
        textAutoCompleter = new TextAutoCompleter(marca);
        textAutoCompleter.setMode(0);
        textAutoCompleter.setCaseSensitive(false);
        try {
            cn = local_connection.getconnect();
        } catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);        }
    iniciarValores();
    cargarProveedores();
}
    // Funcion que convierte un stream de bytes en imagen
    private Image ConvertirImagen(byte[] bytes,String ext) throws IOException {
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        Iterator readers = ImageIO.getImageReadersByFormatName(ext);
        ImageReader reader = (ImageReader) readers.next();
        Object source = bis; // File or InputStream
        ImageInputStream iis = ImageIO.createImageInputStream(source);
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
        return reader.read(0, param);
    } 
    
    private void iniciarValores() {
        fecha.setVisible(false);
             fecha.setEnabled(false);
        try {
            ps =   (PreparedStatement) cn.prepareStatement("SELECT activo, nombre, modelo, descripcion, peso, notas, tipo,tipo_cantidad,marca,id_proveedor from productos where id_producto = "+code);
         rs = ps.executeQuery();
         rs.next();
         if(rs.getString("marca")!=null)marca.setText(rs.getString("marca"));
         nombre.setText(rs.getString("nombre"));
         codigo.setText(String.valueOf(code));
         peso.setText(rs.getString("peso"));
         modelo.setText(rs.getString("modelo"));
//         especificaciones.setText(rs.getString("especificaciones"));
         notas.setText(rs.getString("notas"));
         descripcion.setText(rs.getString("descripcion"));
         comboTipoCantidad.setSelectedItem(rs.getString("tipo_cantidad"));
         if (rs.getString("tipo").equals("Producto"))
             tipo.setSelectedIndex(0); 
         if (rs.getString("tipo").equals("Servicio"))
             tipo.setSelectedIndex(1);
         if (rs.getString("tipo").equals("Curso")){
             tipo.setSelectedIndex(2);
         fecha.setVisible(true);
             fecha.setEnabled(true);
         }
         id_proveedor=rs.getInt("id_proveedor");
         activo.setSelectedIndex(rs.getInt("activo"));
         // Buscamos la imagen en la base de datos.
         ps =   (PreparedStatement) cn.prepareStatement("SELECT * FROM archivos a,archivo_relacion b WHERE a.id = b.archivoId AND b.productoId = "+code);
         rs = ps.executeQuery();
         if(!rs.next()){
                imageProduct.setText("No existe imagen en la BD");               
            } else {
                int imgMax = Integer.parseInt(imageMax.getText());
                imageCurrent.setText("1");
                do{
                    // Sumamos +1 al numero de imagenes por cada iteracion
                    imgMax+=1;
                    imageMax.setText(String.valueOf(imgMax));
                    ext.addElement(rs.getString("ext"));
                    img.addElement(ConvertirImagen(rs.getBytes("archivo"),(String)ext.get(0)));
                    imgId.addElement(rs.getInt("id"));
                    imageProduct.setIcon(new ImageIcon(((Image)img.get(0)).getScaledInstance(200, 148, 10)));
                } while (rs.next()); // Cicla mientras sigan habiendo lineas en el result set
                if(imgMax > 0){
                    buttonleft.setEnabled(true);
                    buttonright.setEnabled(true);
                    buttonBorrar.setEnabled(true);
                }
            } 
         //textAutoCompleter.addItem(" ");
          ps = (PreparedStatement) cn.prepareStatement("select marca from productos group by marca");
            rs = ps.executeQuery();
            while (rs.next()) {
                if(rs.getString(1)!=null)
                textAutoCompleter.addItem(rs.getString(1));
            }
            
        } catch (SQLException | IOException ex) {
            Almacen.logger.log(Level.SEVERE, null, ex); }
    }
@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        fileChooser = new javax.swing.JFileChooser();
        jLabel7 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        notas = new javax.swing.JTextArea();
        imageProduct = new javax.swing.JLabel();
        examinar = new javax.swing.JButton();
        upload = new javax.swing.JButton();
        buttonleft = new javax.swing.JButton();
        buttonright = new javax.swing.JButton();
        buttonBorrar = new javax.swing.JButton();
        imageCurrent = new javax.swing.JLabel();
        imageMax = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        codigo = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        fecha = new javax.swing.JButton();
        nombre = new javax.swing.JTextField();
        categorias = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        activo = new javax.swing.JComboBox();
        aceptar = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        comboTipoCantidad = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        salir = new javax.swing.JButton();
        comboProveedor = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        descripcion = new javax.swing.JTextArea();
        tipo = new javax.swing.JComboBox();
        jLabel22 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        modelo = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        marca = new javax.swing.JTextField();
        peso = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Propiedades");
        setIconImage(new ImageIcon(getClass().getResource("/resources/logo_rayito.png")).getImage());
        setMinimumSize(new java.awt.Dimension(500, 400));
        setResizable(false);

        jLabel7.setText("Notas:");

        notas.setColumns(15);
        notas.setLineWrap(true);
        notas.setRows(5);
        notas.setWrapStyleWord(true);
        notas.setMaximumSize(new java.awt.Dimension(200, 145));
        notas.setNextFocusableComponent(aceptar);
        jScrollPane3.setViewportView(notas);

        imageProduct.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        examinar.setText("Nueva");
        examinar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                examinarActionPerformed(evt);
            }
        });

        upload.setFont(new java.awt.Font("Tahoma", 0, 8)); // NOI18N
        upload.setText("Cambiar");
        upload.setEnabled(false);
        upload.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                uploadActionPerformed(evt);
            }
        });

        buttonleft.setText("<<");
        buttonleft.setEnabled(false);
        buttonleft.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonleftActionPerformed(evt);
            }
        });

        buttonright.setText(">>");
        buttonright.setEnabled(false);
        buttonright.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonrightActionPerformed(evt);
            }
        });

        buttonBorrar.setText("Borrar");
        buttonBorrar.setEnabled(false);
        buttonBorrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonBorrarActionPerformed(evt);
            }
        });

        imageCurrent.setText("0");

        imageMax.setText("0");

        jLabel9.setText("/");

        jLabel1.setText("Activo:");

        jLabel10.setText("Vender por:");

        jLabel11.setText("Peso:");

        codigo.setNextFocusableComponent(peso);

        jButton1.setText("Modificar Especifiaciones");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        fecha.setText("Fecha");
        fecha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fechaActionPerformed(evt);
            }
        });

        nombre.setNextFocusableComponent(descripcion);

        categorias.setText("Categorias");
        categorias.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                categoriasActionPerformed(evt);
            }
        });

        jLabel5.setText("Descripcion General:");

        activo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "No", "Si" }));
        activo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                activoActionPerformed(evt);
            }
        });

        aceptar.setText("Aceptar");
        aceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aceptarActionPerformed(evt);
            }
        });

        jLabel6.setText("Proveedor:");

        jLabel4.setText("Nombre:");

        jLabel3.setText("gr");

        comboTipoCantidad.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Pieza", "Kilogramo", "Litro" }));

        jLabel2.setText("Tipo:");

        salir.setText("Salir");
        salir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                salirActionPerformed(evt);
            }
        });

        descripcion.setColumns(20);
        descripcion.setLineWrap(true);
        descripcion.setRows(5);
        descripcion.setWrapStyleWord(true);
        descripcion.setMaximumSize(new java.awt.Dimension(305, 94));
        descripcion.setMinimumSize(new java.awt.Dimension(305, 22));
        descripcion.setPreferredSize(new java.awt.Dimension(305, 94));
        jScrollPane1.setViewportView(descripcion);

        tipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Producto", "Servicio", "Curso" }));
        tipo.setNextFocusableComponent(nombre);
        tipo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tipoActionPerformed(evt);
            }
        });

        jLabel22.setText("Marca:");

        jLabel8.setText("Modelo:");

        modelo.setNextFocusableComponent(tipo);

        jButton2.setText("Agregar Proveedor");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        peso.setNextFocusableComponent(modelo);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel8)
                            .addComponent(jLabel2)
                            .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4)
                            .addComponent(jLabel22)
                            .addComponent(jLabel6))
                        .addGap(26, 26, 26)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(activo, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(codigo, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(peso, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel3))
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(tipo, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(comboTipoCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(marca, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(nombre, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(modelo, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(comboProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(aceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(salir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                            .addComponent(jButton1)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                            .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(18, 18, 18)
                            .addComponent(categorias)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(fecha, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(activo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(codigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11)
                    .addComponent(peso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(modelo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel10)
                    .addComponent(comboTipoCantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel22))
                    .addComponent(marca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(comboProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addGap(11, 11, 11)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(categorias)
                    .addComponent(fecha))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(salir)
                    .addComponent(aceptar))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jLabel7)
                        .addGap(168, 168, 168))
                    .addComponent(imageProduct, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane3)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(buttonleft, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(examinar))
                        .addGap(17, 17, 17)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(imageCurrent)
                                .addGap(34, 34, 34)
                                .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 4, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(imageMax, javax.swing.GroupLayout.PREFERRED_SIZE, 6, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(upload, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 14, Short.MAX_VALUE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(buttonright, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(buttonBorrar, javax.swing.GroupLayout.Alignment.TRAILING))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(imageProduct, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(imageCurrent)
                                        .addComponent(imageMax)
                                        .addComponent(jLabel9))
                                    .addComponent(buttonleft))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(examinar))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(buttonright)
                                .addGap(2, 2, 2)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(buttonBorrar)
                                    .addComponent(upload, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(2, 2, 2)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void activoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_activoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_activoActionPerformed

    private void salirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_salirActionPerformed
        this.dispose();
        // TODO add your handling code here:
    }//GEN-LAST:event_salirActionPerformed

    private void aceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aceptarActionPerformed
        try {
            String name = String.valueOf(comboProveedor.getSelectedItem());
            ps = (PreparedStatement) cn.prepareStatement("SELECT * FROM personas WHERE concat(nombre,' ',paterno,' ',materno)='" + name + "' LIMIT 1");
            rs = ps.executeQuery();
            int persona = 0;
            if (rs.next()) {
                persona = rs.getInt("id_persona");
            }
            if(peso.getText().equals("")) peso.setText("0");
            if(marca.getText().equals("")) marca.setText("");
            queries.doSyncQuery(cn, ps,"UPDATE productos SET activo="+activo.getSelectedIndex()+",nombre ='"+nombre.getText()+
                    "', modelo = '"+modelo.getText()+"', marca= '"+marca.getText()+"',descripcion = '"+descripcion.getText()+"', "
                    + "peso =  "+ peso.getText()+", notas ='"+notas.getText()+"',tipo = '"+tipo.getSelectedItem()+ "',id_proveedor = "+persona+",tipo_cantidad='"+comboTipoCantidad.getSelectedItem().toString()+"' WHERE id_producto ="+code+" LIMIT 1");
         
            System.out.println("UPDATE productos SET activo="+activo.getSelectedIndex()+",nombre ='"+nombre.getText()+
                    "', modelo = '"+modelo.getText()+"', marca= '"+marca.getText()+"',descripcion = '"+descripcion.getText()+"', "
                    + "peso =  "+ peso.getText()+", notas ='"+notas.getText()+"',tipo = '"+tipo.getSelectedItem()+ "',id_proveedor = "+persona+",tipo_cantidad='"+comboTipoCantidad.getSelectedItem().toString()+"' WHERE id_producto ="+code+" LIMIT 1");
//    queries.doSyncQuery(cn, ps, "delete from categorias_productos where id_producto = "+code);
          /*  for (int i = 0; i < editProducto.model2.getSize(); i++) {
                queries.doSyncQuery(cn, ps, "INSERT INTO categorias_productos VALUES ((SELECT id_categoria FROM categorias WHERE nombre = '" + editProducto.model2.get(i) + "')," + code + ")");
            }*/
            
            this.dispose();
            // TODO add your handling code here:
        } catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);        }
    }//GEN-LAST:event_aceptarActionPerformed

    private void fechaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fechaActionPerformed
fechas = new cambiarFecha(this,true,code);
fechas.setVisible(true);
        // TODO add your handling code here:
    }//GEN-LAST:event_fechaActionPerformed

    private void categoriasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_categoriasActionPerformed
            /*editProducto.model2.clear();
            editProducto.model2.removeAllElements();
            ps = (PreparedStatement)cn.prepareStatement("select nombre from categorias join categorias_productos on categorias.id_categoria = categorias_productos.id_categoria where categorias_productos.id_producto = ?");
            ps.setInt(1,code);
            rs = ps.executeQuery();
            while(rs.next()){
                editProducto.model2.addElement(rs.getObject(1));
            }*/
        ArrayList<Integer> ids = new ArrayList(1);
         ids.add(code);
            Categorias categoria;
        categoria = new Categorias(this,true,ids);
            categoria.setVisible(true);
            // TODO add your handling code here:
   
    }//GEN-LAST:event_categoriasActionPerformed

    private void tipoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tipoActionPerformed
if (tipo.getSelectedIndex()!=2&&!Almacen.celulares){
             fecha.setVisible(false);
             fecha.setEnabled(false);
}
else {
 fecha.setVisible(true);
             fecha.setEnabled(true);   
}
        // TODO add your handling code here:
    }//GEN-LAST:event_tipoActionPerformed

    private void examinarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_examinarActionPerformed
        FileNameExtensionFilter filtro = new FileNameExtensionFilter(
        "JPG, PNG & GIF", "jpg", "gif", "jpeg", "png");
        int max=Integer.parseInt(imageMax.getText());
        fileChooser.removeChoosableFileFilter(fileChooser.getAcceptAllFileFilter());
        fileChooser.setFileFilter(filtro);
        int returnVal = fileChooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            try {
                File file = fileChooser.getSelectedFile();
                Image imag = ImageIO.read(file);
                Image resized = imag.getScaledInstance(200, 112, 10);
                ImageIcon icon = new ImageIcon(resized);
                imageCurrent.setText(String.valueOf(max+1));
                imageMax.setText(String.valueOf(max+1));
                img.addElement(imag);
                String exte = file.getName().split("\\.")[1];
                ext.addElement(exte);
                imageProduct.setIcon(icon);
                imageProduct.setText("");
                if(max+1>0){
                    buttonleft.setEnabled(true);
                    buttonright.setEnabled(true);
                    buttonBorrar.setEnabled(true);
                }
                hayImagen=true;
                addImagen();
            } catch (IOException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);            }
        }
    }//GEN-LAST:event_examinarActionPerformed

    public void addImagen(){
        if(hayImagen){
            try {
                int productId = code;
                File file = fileChooser.getSelectedFile();
                FileInputStream fis = new FileInputStream(file);
                java.sql.PreparedStatement st;
                String exten = file.getName().split("\\.")[1];
                // Preparamos query para insertar el archivo
                ps = (PreparedStatement)cn.prepareStatement("INSERT INTO archivos(nombre,ext,archivo) VALUES(?,?,?)",Statement.RETURN_GENERATED_KEYS);
                ps.setString(1, file.getName());  
                ps.setString(2, exten);                
                ps.setBinaryStream(3, fis, (int) file.length());
                ps.executeUpdate();
                // Hacemos relacion con el producto
                rs = ps.getGeneratedKeys();
                rs.next();
                ps = (PreparedStatement)cn.prepareStatement("INSERT INTO archivo_relacion(archivoId,productoId) VALUES(?,?)");
                ps.setInt(1,rs.getInt(1)); 
                ps.setInt(2, productId);
                ps.execute();
                imgId.addElement(rs.getInt(1));
                } catch (    SQLException | FileNotFoundException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);                }
            }
    }   
    private void uploadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uploadActionPerformed
   
    }//GEN-LAST:event_uploadActionPerformed

    private void buttonBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonBorrarActionPerformed
        try {
            int current=Integer.parseInt(imageCurrent.getText());
            int max=Integer.parseInt(imageMax.getText());
            if(current==1 && max==1){
                current=max=0;
                imageProduct.setIcon(null);
                imageProduct.setText("No existe imagen en la BD"); 
                buttonBorrar.setEnabled(false);
                buttonleft.setEnabled(false);
                buttonright.setEnabled(false);
            } else {
                max-=1;
                if(current>max){
                    current=max;
                }
                imageProduct.setIcon(new ImageIcon(((Image)img.get(current-1)).getScaledInstance(200, 148, 10)));
            }
            // Borramos de la BD
            ps = (PreparedStatement)cn.prepareStatement("DELETE FROM archivos WHERE id=?");
            ps.setInt(1,(int)imgId.elementAt(current));
            ps.execute();
            ps = (PreparedStatement)cn.prepareStatement("DELETE FROM archivo_relacion WHERE archivoId=?");
            ps.setInt(1,(int)imgId.elementAt(current));
            ps.execute();
            img.removeElementAt(current);
            imageCurrent.setText(String.valueOf(current));
            imageMax.setText(String.valueOf(max));
        } catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);        }
    }//GEN-LAST:event_buttonBorrarActionPerformed

    private void buttonrightActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonrightActionPerformed
        int current=Integer.parseInt(imageCurrent.getText());
        int max=Integer.parseInt(imageMax.getText());
        if (current==max){
            current=1;
        } else current+=1;
        imageCurrent.setText(String.valueOf(current));
        imageProduct.setIcon(new ImageIcon(((Image)img.get(current-1)).getScaledInstance(200, 148, 10)));
    }//GEN-LAST:event_buttonrightActionPerformed

    private void buttonleftActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonleftActionPerformed
        int current=Integer.parseInt(imageCurrent.getText());
        int max=Integer.parseInt(imageMax.getText());
        if (current==1){
            current=max;
        } else current-=1;
        imageCurrent.setText(String.valueOf(current));
        imageProduct.setIcon(new ImageIcon(((Image)img.get(current-1)).getScaledInstance(200, 148, 10)));
    }//GEN-LAST:event_buttonleftActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
(new Especificaciones(code)).setVisible(true);
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        (new agregarProvedor(this, true, 0)).setVisible(true);
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed
public static void cargarProveedores() {
        try {
            int banderaProveedor=0;
            comboProveedor.removeAllItems();
            Connection cn = local_connection.getconnect();
            PreparedStatement ps = (PreparedStatement) cn.prepareStatement("SELECT concat(nombre,' ',paterno,' ',materno),id_persona FROM personas WHERE tipo ='Proveedor'");
            ResultSet rs = ps.executeQuery();
            for (int i=0;rs.next();i++) {
                comboProveedor.addItem(rs.getString("concat(nombre,' ',paterno,' ',materno)"));
                if(rs.getInt(2)==id_proveedor)
                    banderaProveedor=i;
            }
            comboProveedor.setSelectedIndex(banderaProveedor);
        } catch (SQLException ex) {
Almacen.logger.log(Level.SEVERE, null, ex);        }
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton aceptar;
    private javax.swing.JComboBox activo;
    private javax.swing.JButton buttonBorrar;
    private javax.swing.JButton buttonleft;
    private javax.swing.JButton buttonright;
    private javax.swing.JButton categorias;
    private javax.swing.JTextField codigo;
    private static javax.swing.JComboBox comboProveedor;
    private javax.swing.JComboBox comboTipoCantidad;
    private javax.swing.JTextArea descripcion;
    private javax.swing.JButton examinar;
    private javax.swing.JButton fecha;
    private javax.swing.JFileChooser fileChooser;
    private javax.swing.JLabel imageCurrent;
    private javax.swing.JLabel imageMax;
    private javax.swing.JLabel imageProduct;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel22;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextField marca;
    private javax.swing.JTextField modelo;
    private javax.swing.JTextField nombre;
    private javax.swing.JTextArea notas;
    private javax.swing.JTextField peso;
    private javax.swing.JButton salir;
    private javax.swing.JComboBox tipo;
    private javax.swing.JButton upload;
    // End of variables declaration//GEN-END:variables
cambiarFecha fechas;
}
